<template>
	<view class="pro-body">
	
		<view class="body" >
			<view class="top-container">
				<view class="date-row">
				    <view class="date-label">单据日期：</view>
				    <uni-datetime-picker
				      ref="datetimePicker"
				      v-model="header.fdate"
				      type="date"
				      @change="onInStockTimeChange"
				      :placeholder="'请选择日期时间'"
				      class="date-picker"
				    />
				  </view>
				<uni-list :border="false" >
					<uni-list-item :border="false" title="单据编号"  :rightText="header.billNo" />
					<uni-list-item :border="false" title="件号"  :rightText="header.specification" />
					<uni-list-item :border="false" title="物料名称"  :rightText="header.materialName" />
					<uni-list-item :border="false" title="数量"  	:rightText="String(header.qty)" />
					<uni-list-item :border="false" title="工序说明"  :rightText="header.describe1" />

				</uni-list>
				
			</view>
			
			<template v-if="detail && detail.length > 0" >
		
				<uni-swipe-action-item class="" v-for="(item,index) in detail" :left-options="options" @click="handleDelete(item)" :key = "index">
					<view class="panel">
						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">托盘编号：</view>
									<view class="panel_content_row_item_value">{{ item.trayno }}</view>
								</view>
							</view>
						</view>
								
						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">物料名称：</view>
									<view class="panel_content_row_item_value">{{ item.fmaterialname }}</view>
								</view>
							</view>
						</view>
						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">物料编码：</view>
									<view class="panel_content_row_item_value">{{ item.fmaterialnumber }}</view>
								</view>
							</view>
						</view>
						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">单位：</view>
									<view class="panel_content_row_item_value">{{ item.funitname }}</view>
								</view>
							</view>
						</view>

						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">领料数量：</view>
									<view class="panel_content_row_item_value">{{ item.finfactqty }}</view>
									<!-- 打印按钮 -->
									<!-- <button class="print-btn" @click="printText(item)">打印</button> -->
								</view>
							</view>
						</view>
					</view>
				</uni-swipe-action-item>	
			
			</template>
		
		<uni-empty-info v-else label="暂无领料信息"></uni-empty-info>
			
			<button @click="printContect" class="footerBtn save" ><i
					class="iconfont icon-duihao btn_icon" ></i>连接打印机
			</button>

			<!-- <button @click="printText" class="footerBtn save" ><i
					class="iconfont icon-duihao btn_icon" ></i>打印
			</button> -->
		</view>	
		<!--  底部按钮  -->
		<view class="footerPanel">
			<view class="footerPanel_body">
				<button @click="pickScan" class="footerBtn scan" type="primary"><i
						class="iconfont icon-saomiao btn_icon"></i>扫码
				</button>
				<button @click="savePickBill" class="footerBtn save" ><i
						class="iconfont icon-duihao btn_icon" ></i>生成领料单
				</button>
				
			</view>
		</view>
		<!-- 获取托盘信息 -->
		<GetTray ref="trayRef" @success="getTraySuccess"></GetTray>
		
		<!-- 扫描托盘 -->
		<tray-popup ref="trayPopupRef" @success="trayScanningScuess"></tray-popup>
		 
</view>
</template>

<script>
	import uniTransition from 'uni_modules/uni-transition/components/uni-transition/uni-transition.vue';
	import uniEmptyInfo from "../../vBase/components/uni-empty-info/uni-empty-info.vue"
	import {getProPlanDetail,
	savePickBill,
	deletePickDetailTemp,
	getTray,
	getMacByUuid
	} from '@/utils/api.js'
	import GetTray from "../pop/get_tray.vue"
	import trayPopup from '../../components/popup/trayPopup.vue'
	import {printContect,
	printQRCode,
	printData,
	printVerticalLabel,
	printTextAndQRCode} from '@/utils/print.js'
	
	// const printModule = uni.requireNativePlugin('PrintModuleCPCL');

	export default {
		components: {
			GetTray,
			uniEmptyInfo,
			trayPopup
		},
		data(){
			return{
				billNo: '',
				loading: true,
				header:{},
				detail:[],
				trayData:{},
				inStockTime: '',
				
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#FF4E74'
					}
				}],
			}
	},
	methods:{
	

		formatDateTime(date) {
			const y = date.getFullYear();
			const m = String(date.getMonth() + 1).padStart(2, '0');
			const d = String(date.getDate()).padStart(2, '0');
			const h = String(date.getHours()).padStart(2, '0');
			const min = String(date.getMinutes()).padStart(2, '0');
			const s = String(date.getSeconds()).padStart(2, '0');
			return `${y}-${m}-${d} ${h}:${min}:${s}`;
		},
		getTodayDateTime() {
			return this.formatDateTime(new Date());
		},
		onInStockTimeChange(val) {
			// 有些端返回时间戳或 ISO 格式，这里统一转成 yyyy-MM-dd HH:mm:ss
			if (typeof val === 'string') {
				this.inStockTime = val.length > 19 ? val.slice(0, 19).replace('T', ' ') : val
			} else {
				this.inStockTime = this.formatDateTime(new Date(val))
			}
		},
	    requestBluetoothPermission(callback) {
	        if (plus.os.name !== "Android") {
	            callback(true); // iOS 直接返回
	            return;
	        }
	
	        const permissions = [
	            "android.permission.BLUETOOTH_SCAN",
	            "android.permission.BLUETOOTH_CONNECT",
	            "android.permission.ACCESS_FINE_LOCATION"
	        ];
	
	        const main = plus.android.runtimeMainActivity();
	        const PackageManager = plus.android.importClass("android.content.pm.PackageManager");
	        const ActivityCompat = plus.android.importClass("androidx.core.app.ActivityCompat");
	
	        let allGranted = true;
	
	        for (let i = 0; i < permissions.length; i++) {
	            const perm = permissions[i];
	            const result = ActivityCompat.checkSelfPermission(main, perm);
	            if (result !== PackageManager.PERMISSION_GRANTED) {
	                allGranted = false;
	                break;
	            }
	        }
	
	        if (allGranted) {
	            callback(true);
	            return;
	        }
	
	        // 请求权限
	        ActivityCompat.requestPermissions(main, permissions, 1);
	
	        // 简单处理：延迟一会儿再假设用户已经同意（实际可以用 plus.android.requestPermissionsResult 监听）
	        setTimeout(() => {
	            callback(true);
	        }, 500);
	    },


		//蓝牙连接打印机
		printContect(){
			let uuid = plus.device.uuid; 
			//获取打印机mac
			getMacByUuid({uuid:uuid}).then(res => { 
				if (res.data.status === 200){
					const macAddress = res.data.data.macAdress
					this.requestBluetoothPermission((granted) => {
						if (!granted) {
							uni.showToast({ title: '蓝牙权限未授权', icon: 'none' });
							return;
						}
						const printModule = uni.requireNativePlugin('PrintModuleCPCL');
						// const macAddress = '6C:C1:47:01:31:75'; // 替换成你的打印机MAC
						printContect(macAddress)
	
					});
				}
			})


		},

		//添加成功后返回
		getTraySuccess(e){
			this.initData()
			//托盘添加成功后直接打印二维码，如果断开连接手动连接
			// this.printText();
		},
		/**
		 * 删除物料
		 * @param {Object} e
		 */
		handleDelete(item) {
			
			const self = this
			uni.showModal({
				title: '提示',
				content: '是否删除物料？',
				success(res) {
					if (res.confirm){
						deletePickDetailTemp({moBillNo : self.header.moBillNo,pickDetail : item}).then(res => {
							if (res.data.data){
								uni.showToast({
									title:'删除成功',
									icon:'none'
								})
							}
							self.initData()
						})
					}
					
				}
			})
		},
		
		savePickBill(){
			let _this = this
			if (this.detail.length == 0 || this.detail == null){
				uni.showToast({
					title:'当前没有数据，请先扫描托盘',
					icon:'none'
				})
					return;
			}
			uni.showModal({
				title:'提示',
				content:'确认保存领料单',
				success(res) {
					if (res.confirm){
						savePickBill({billNo :_this.header.billNo,
						moBillNo :_this.header.moBillNo ,
						detail : _this.detail,
						inStockTime:_this.inStockTime}).then(result => {
						if (result.data.data){
							uni.showToast({
								title:'领料成功',
								icon:'none'
							})
						}
						_this.initData()
						})
					
					}
				}
			})
		},
		//扫码成功后返回
		trayScanningScuess(e){
			let _this = this;
			getTray({billNo : e,moBillNo : this.header.moBillNo}).then(result => {
				if (result.statusCode == 200){
					this.trayData = result.data.data ?? {}
						let param = {
							title: '托盘信息',
							trayData: _this.trayData,
							header : _this.header,
							type : 'pick'
						}
						//如果托盘上的信息不是当前bom的不让领料，走补料
						if(!_this.trayData.isPpBom){
							uni.showModal({
								content:'托盘信息不属于bom中的，请走补料',
								title:'提示',
								showCancel: false
							})
							return;
						}
						this.$refs.trayRef.open(param)
					
					
				}
			})
		},
		//扫码获取领料信息
		pickScan(){
			this.$refs.trayPopupRef.open()
		},
		// 获取详情数据
		initData(){
			getProPlanDetail({billNo :this.billNo }).then(res => {
				if (res.statusCode == 200){
					this.header = res.data.data.data
					this.detail = res.data.data.dataList
					this.inStockTime= this.header.fdate || this.getTodayDateTime()
				
				} 
			})

		}
	},
	watch: {
		userInfo() {
			
			}
		},
		mounted() {
			this.initData()

		},
	onLoad(e){
		this.billNo = e.billNo
		
	}
}
</script>

<style lang="scss" scoped>
	@import "../../static/css/common";
	::v-deep .uni-list-item__extra {
	    pointer-events: auto !important;
	}
/* 调整列表项左右文字大小 */
::v-deep .uni-list-item__content-title {
    font-size: 22px !important;  /* 左侧标题字体大小 */
	padding-left: 5px;
}
::v-deep .uni-list-item__extra-text {
    font-size: 22px !important;  /* 右侧内容字体大小 */
	padding-right: 5px;
	 color: #333;
}
/* 调整行间距 */
::v-deep .uni-list-item__container {
    padding: 3px 0 !important;   /* 减小上下内边距 */
    min-height: 10px !important; /* 减小最小高度 */
}

.panel {
  background: #fbffe2;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}
 
/* 调整标题样式 */
.panel_content_row_item_title {
    font-size: 17px !important;  /* 调大字体 */
    color: #000000 !important;   /* 纯黑字体 */
    flex-shrink: 0;             /* 防止压缩 */
}
/* 调整标题样式 */
.panel_content_row_item_value {
  flex: 1;
  font-size: 17px !important; /* 数值特别放大 */
  color: #333 !important;
}
// .print-btn {
//   margin-left: 10px;
//   height: 28px;
//   line-height: 28px;
//   padding: 0 12px;
//   font-size: 14px;
//   background-color: #409EFF; /* 蓝色按钮 */
//   color: #fff;
//   border-radius: 6px;
// }
// .flex-row {
//   display: flex;
//   align-items: center;
// }

/* 底部按钮 - 修改布局 */
	.footerPanel {
	  height: 60px;
	  .footerPanel_body {
	    display: flex;
	    justify-content: space-between; /* 左右分布按钮 */
	    width: 100%;
	    padding: 0 10px;
	    box-sizing: border-box;
	    
	    .footerBtn {
	      height: 50px;
	      min-width: 115px;
	      display: flex;
	      line-height: 1;
	      font-size: 20px; /* 适当增大字体 */
	      border-radius: 8px;
	      align-items: center;
	      justify-content: center;
	      box-shadow: 0 2px 5px rgba(0,0,0,0.2);
	      color: #fff;
	      border: none;
	      // margin: 0 10px;
	    }
	  }
	}
.date-row {
  display: flex;
  align-items: center;

}

.date-label {
  font-size: 18px;
  width: 100px; /* 左侧固定宽度 */
  color: #333;
}

.date-picker {
  flex: 1; /* 占满剩余空间 */
  font-size: 18px;
  color: #333;
}
</style>